import React, { useCallback, useMemo, useLayoutEffect } from 'react';
import { useActions, useProps, useDevice } from '@ray-js/panel-sdk';
import {
  View,
  Image,
  Text,
  ScrollView,
  router,
  publishDps,
  exitMiniProgram,
  navigateTo,
  hideMenuButton,
} from '@ray-js/ray';
import { NavBar } from '@ray-js/smart-ui';
import clsx from 'clsx';
import styles from './index.module.less';
import Slider from '@/components/Slider';
import Slider2 from '@/components/Slider2';
import SliderSingle from '@/components/SliderSingle';

import CurtainDisplay from '@/components/curtainDisplay';
import CurtainDisplay2 from '@/components/curtainDisplay2';
import CurtainDisplaySingle from '@/components/curtainDisplaySingle';

import Strings from '@/i18n';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import res from '@/res';

const sysInfo = getCachedSystemInfo();

const HeaderHeight = 59;

export default function Home() {
  const {
    control,
    control_2,
    percent_control,
    work_state,
    situation_set,
    percent_control_2,
    curtain_mode,
    percent_state,
    percent_state_2,
  } = useProps();

  const deviceName = useDevice(d => d.devInfo.name);
  const deviceId = useDevice(d => d.devInfo.devId);
  const groupId = useDevice(d => d.devInfo.groupId);

  const actions = useActions();

  const convert = useCallback(
    value => {
      return value;
    },
    [situation_set]
  );

  const reverse = useCallback(
    value => {
      return value;
    },
    [situation_set]
  );

  const convertPercent = useMemo(() => convert(percent_control), [percent_control, situation_set]);

  const leftState = percent_state;
  const rightState = percent_state_2;

  const convertPercent2 = useMemo(
    () => convert(percent_control_2),
    [percent_control_2, situation_set]
  );

  const onChangend = useCallback(
    e => {
      const nextPercent = reverse(e.detail.value.percent);

      const { type } = e.detail.value;

      if (type) {
        if (type === 'right') {
          actions.percent_control_2.set(nextPercent);
        } else {
          actions.percent_control.set(nextPercent);
        }
      } else if (curtain_mode === 'same') {
        actions.percent_control.set(nextPercent);
      } else {
        actions.percent_control.set(nextPercent);
        actions.percent_control_2.set(100 - nextPercent);
      }
    },

    [percent_control, situation_set, actions, percent_control_2, curtain_mode]
  );

  const controls = [
    {
      name: 'open',
      image: res.open0,
      activeImage: res.open1,
    },
    {
      name: 'stop',
      image: res.stop0,
      activeImage: res.stop1,
    },
    {
      name: 'close',
      image: res.close0,
      activeImage: res.close1,
    },
  ];

  const func = [
    {
      name: 'schedule',
      image: res.schedule,
      onClick: () => {
        router.push(`/timer`);
      },
      descrip: 'scheduleTip',
    },

    {
      name: 'set',
      image: res.set,
      onClick: () => {
        router.push(`/set`);
      },
      descrip: 'setTip',
    },
  ];
  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const onClickLeft = () => {
    console.log('exit=====>>>>');
    exitMiniProgram();
  };

  const getLeftPosition = () => {
    return leftState;
  };

  const getRightPositon = () => {
    if (curtain_mode === 'same') return leftState;
    if (curtain_mode === 'conflict') {
      return '';
    }

    return rightState;
  };

  const renderCurtain = () => {
    return (
      <View
        className={styles.curtain}
        style={{
          overflow: 'hidden',
        }}
      >
        <View
          style={{
            position: 'relative',
            zIndex: 200,
            top: -topCurtainMap[curtain_mode],
            height: 1620,
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          <View
            style={{
              position: 'relative',
              height: 540,
              width: '100%',
            }}
          >
            <CurtainDisplay // same
              control={control}
              leftValue={convertPercent}
              rightValue={convertPercent}
              leftStateValue={leftState}
              rightStateValue={leftState}
            />
          </View>
          <View
            style={{
              position: 'relative',
              height: 540,
              width: '100%',
            }}
          >
            <CurtainDisplaySingle
              control={control}
              control2={control_2}
              leftValue={convertPercent}
              rightValue={convertPercent2}
              leftStateValue={leftState}
              rightStateValue={rightState}
            />
          </View>

          <View
            style={{
              position: 'relative',
              height: 540,
              width: '100%',
            }}
          >
            <CurtainDisplay2 // confict
              control={control}
              leftValue={convertPercent}
              rightValue={100 - convertPercent}
              leftStateValue={leftState}
              rightStateValue={rightState}
            />
          </View>
        </View>
      </View>
    );
  };

  const topMap = {
    same: 0,
    single: 100,
    conflict: 200,
  };

  const topCurtainMap = {
    same: 0,
    single: 540,
    conflict: 1080,
  };

  return (
    <View className={styles.view}>
      <NavBar
        leftArrow
        onClickLeft={onClickLeft}
        title={deviceName}
        className={styles.navBar}
        slot={{
          right: (
            <View className={styles.tabTopIconWrap}>
              {['setting'].map(item => (
                <Image
                  onClick={() => {
                    console.log('点击设置');
                    const jumpUrl = `functional://settings/detail?deviceId=${
                      deviceId || ''
                    }&groupId=${groupId || ''}`;

                    navigateTo({
                      url: jumpUrl,
                    });

                    // tabItem?.callback();
                  }}
                  src={res.setting}
                  key={item}
                />
              ))}
            </View>
          ),
        }}
      />

      <ScrollView
        scrollY
        refresherTriggered
        // className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(100vh - ${HeaderHeight}px - ${sysInfo.statusBarHeight}px)`,
        }}
      >
        <View className={styles.curtainBox}>{renderCurtain()}</View>

        <View className={styles.card}>
          <View className={styles.textBox}>
            <View>
              <Text className={styles.postion}>
                {Strings.getLang(curtain_mode !== 'conflict' ? 'leftPosition' : 'conflitPosition')}
              </Text>
              <View className={styles.postionValue}>{getLeftPosition()}%</View>
            </View>
            <View
              style={{
                textAlign: 'right',
              }}
            >
              <Text className={styles.postion}>
                {getRightPositon() !== '' ? Strings.getLang('rightPosition') : ''}
              </Text>
              <View className={styles.postionValue}>
                {getRightPositon() !== '' ? `${getRightPositon()}%` : ''}
              </View>
            </View>
          </View>
          <View
            className={styles.slider}
            style={{
              overflow: 'hidden',
            }}
          >
            <View
              style={{
                position: 'relative',
                zIndex: 200,
                top: -topMap[curtain_mode],
                height: 300,
                width: '100%',
                display: 'flex',
                flexDirection: 'column',
              }}
            >
              <View
                style={{
                  position: 'relative',
                  height: 100,
                  width: '100%',
                }}
              >
                <Slider // same
                  control={control}
                  leftValue={convertPercent}
                  rightValue={convertPercent}
                  bindchangend={onChangend}
                  mode="same"
                />
              </View>
              <View
                style={{
                  position: 'relative',
                  height: 100,
                  width: '100%',
                }}
              >
                <SliderSingle // single
                  key="single"
                  leftValue={convertPercent}
                  rightValue={convertPercent2}
                  bindchangend={onChangend}
                  mode="single"
                />
              </View>

              <View
                style={{
                  position: 'relative',
                  height: 100,
                  width: '100%',
                }}
              >
                <Slider2 // conflict
                  key="conf"
                  control={control}
                  leftValue={convertPercent}
                  bindchangend={onChangend}
                  lock={control !== 'close'}
                />
                {control !== 'close' ? (
                  <View
                    style={{
                      position: 'absolute',
                      background: 'rgba(0, 0, 0, 0.2)',
                      height: 80,
                      width: '100%',
                      top: 0,
                      left: 0,
                      zIndex: 20,
                      pointerEvents: 'none',
                      borderRadius: 40,
                    }}
                  >
                    <Image src={res.lock} className={styles.lockImage} />
                  </View>
                ) : null}
              </View>
            </View>
          </View>
        </View>

        <View className={styles.card}>
          <View className={styles.controlBox}>
            {controls.map(item => (
              <View
                key={item.name}
                className={styles.control}
                onClick={() => {
                  const dps = {
                    control: item.name,
                  };

                  publishDps(dps);
                }}
              >
                <Image
                  className={styles.controlIcon}
                  src={control === item.name ? item.activeImage : item.image}
                />
                <Text className={styles.controlText}>
                  {Strings.getLang((curtain_mode !== 'single' ? '' : 'left') + item.name)}
                </Text>
              </View>
            ))}
          </View>
        </View>

        {curtain_mode === 'single' ? (
          <View className={styles.card}>
            <View className={styles.controlBox}>
              {controls.map(item => (
                <View
                  key={item.name}
                  className={styles.control}
                  onClick={() => {
                    const dps = {
                      control_2: item.name,
                    };

                    publishDps(dps);
                  }}
                >
                  <Image
                    className={styles.controlIcon}
                    src={control_2 === item.name ? item.activeImage : item.image}
                  />
                  <Text className={styles.controlText}>{Strings.getLang(`right${item.name}`)}</Text>
                </View>
              ))}
            </View>
          </View>
        ) : null}

        <View className={clsx(styles.card, styles.transparent)}>
          <View className={styles.funcBox}>
            {func.map((item, index) => (
              <View
                key={item.name}
                className={clsx(styles.funcControl, index === 1 && styles.funcControl_2)}
                onClick={item.onClick}
              >
                <View className={styles.setBox}>
                  <Text>{Strings.getLang(item.name)}</Text>
                </View>
                <Image className={styles.funcIcon} src={item.image} />
              </View>
            ))}
          </View>
        </View>
      </ScrollView>
    </View>
  );
}
